﻿/*
 * $Author: ammar $
 * 
 * $Date: 2012-03-09 21:45:14 +0100 (vr, 09 mrt 2012) $
 * $LastChangedBy: ammar $
 * $LastChangedRevision: 92 $
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TLD_Vision.filters;
using System.Drawing;
using System.Diagnostics;

namespace TLD_Vision.OCR
{
	// Simple class to detect the characters bounding box
	public static class CharacterRectangle
	{
		public static Rectangle FindCharacterRectangle(this TLD_Vision.Image sourceImage)
		{
			return FindCharacterRectangle(sourceImage, 0);
		}

		public static Rectangle FindCharacterRectangle(this TLD_Vision.Image sourceImage, int padding)
		{
			{
				Rectangle rect = new Rectangle();
				int x1 = sourceImage.Width, x2 = 0, y1 = sourceImage.Height, y2 = 0;

				unsafe
				{
					uint* pSrc = (uint*)sourceImage.GetDataPointer();
					uint pixel;

					// Iterate over all pixels
					for(int py = 0; py < sourceImage.Height; py++)
					{
						for(int px = 0; px < sourceImage.Width; px++)
						{
							pixel = pSrc[px] & 0x00FFFFFF;

							// Only check if its a dark pixel
							if(pixel < 0x050505)
							{
								if(px < x1)
									x1 = px;
								else if(px > x2)
									x2 = px;

								if(py < y1)
									y1 = py;
								else if(py > y2)
									y2 = py;
							}
						}

						pSrc += sourceImage.Width;
					}
				}

				sourceImage.Unlock();

				rect.X = x1;
				rect.Y = y1;
				rect.Width = x2 - rect.X;
				rect.Height = y2 - rect.Y;

				rect.X -= padding;
				rect.Y -= padding;
				rect.Width += 2 * padding;
				rect.Height += 2 * padding;
                
				return rect;
			}
		}
	}
}